package com.allianz.webapps.controllers;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import sun.misc.BASE64Decoder;

import com.allianz.frame.utils.PropertiesUtil;
import com.allianz.webapps.https.interfaces.type001.pojo.User;
import com.github.pagehelper.StringUtil;

//http://localhost:8080/pad_marketing/main/updateUser.action

@Controller
@RequestMapping(value="main")
public class UpdateController {

	protected final Logger logger = LoggerFactory.getLogger(getClass()); 
	
	/**
	 * 上传图片，保存
	 * @throws Exception 
	 */
	@RequestMapping(value="updateUser")
	@ResponseBody
	public String updateUser(HttpServletRequest request,HttpServletResponse response) throws Exception{
		User user=(User)request.getSession().getAttribute("username");
		String image = request.getParameter("image");//这个就是前端传来的base64图片数据
		if(!com.allianz.frame.utils.StringUtil.notNull(image)){
			throw new Exception("不能上传空的图片");
		}
		//  获取服务器路劲，以userId作为文件夹名称
		String serverPath= PropertiesUtil.getResourcePath()+"private/paper/"+user.getUserIntId();
		logger.info("======服务器文件夹路径：====="+serverPath);
		File files=new File(serverPath);
		//判断文件夹是否存在
		if(!files.isFile() && !files.exists()){
			files.mkdirs();
		}
		//判断文件夹里是否有图片，有就删除文件
		if(files.listFiles().length>0){
			for (File f : files.listFiles()) {
				f.delete();
			}
		}
		//  以userIntId作为头像名称
		String path = serverPath+"/"+user.getUserIntId()+".jpg";
		logger.info("===============文件完整路劲:==========="+path);
		logger.info("文件完整路劲 serverPath:"+path);
		image=image.substring(image.indexOf(",")+1);
		boolean state = false;
		BASE64Decoder decoder = new BASE64Decoder();
		try{
			byte[] decodedBytes = decoder.decodeBuffer(image);
			for(int i=0;i<decodedBytes.length;++i){  
				if(decodedBytes[i]<0){//调整异常数据  
                	decodedBytes[i]+=256;  
                }
			}
			FileOutputStream out = new FileOutputStream(path);
			out.write(decodedBytes);
			out.close();
			File file =new File(path);
			
			//  压缩图片
//			ImgCompress imgCom = new ImgCompress(file);  
//	        imgCom.resizeFix(299, 299,path);
	        
	        
			logger.info("photo upload success.");
			state = true;
		}catch(Exception e){
			logger.info("photo upload faild.");
			state = false;
		}finally{
			//ftpService.logout();
		}
		request.getSession().setAttribute("username", user);
		return state+"";
	}
	
	/**
	 * 获取user对象,同时获得图片路劲
	 */
	@RequestMapping(value="getUser")
	@ResponseBody
	public Map<String,Object> getUser(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> map=new HashMap<String,Object>();
		User user = (User)request.getSession().getAttribute("username");
		if(user==null || StringUtil.isEmpty(user.getUserIntId())){
			return null;
		}
		map.put("username", user);
		map.put("imgUrl",null);
		String userIntId = user.getUserIntId();
		File file = new File(PropertiesUtil.getResourcePath()+"private/paper/"+userIntId);
		if(file.exists() && !file.isFile()){
			if(file.listFiles().length>0){
				map.put("imgUrl","/pad_marketing/main/showUserImg.action?userIntId="+userIntId);
			}
		}
		return map;
	}
	
	/**
	 * 获得图片路劲
	 */
	@RequestMapping(value="getImage")
	@ResponseBody
	public Map<String,Object> getImage(HttpServletRequest request,HttpServletResponse response){
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("imgUrl",null);
		String userIntId = request.getParameter("userIntId");
		File file = new File(PropertiesUtil.getResourcePath()+"private/paper/"+userIntId);
		if(file.exists() && !file.isFile()){
			if(file.listFiles().length>0){
				map.put("imgUrl","/pad_marketing/main/showUserImg.action?userIntId="+userIntId);
			}
		}
		
		return map;
	}
	
	/**
	 * 显示图片
	 * @throws IOException 
	 */
	@RequestMapping(value="showUserImg")
	public void showUserImg(HttpServletRequest request,HttpServletResponse response) throws IOException{
		String userIntId = request.getParameter("userIntId");
		String path=PropertiesUtil.getResourcePath()+"private/paper/"+userIntId;
		File file = new File(path);
		String name=file.listFiles()[0].getName();
		File f=new File(path+"/"+name);
		int length = 0;
		ServletOutputStream op = response.getOutputStream();
		response.setContentLength((int) f.length());
		response.setContentType("image/jpeg");
		response.setHeader("Content-Disposition", "inline; filename="+name);
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "No-cache");
		response.setHeader("Cache-Control", "no-store");
		response.setDateHeader("Expires", 0);

		byte[] bytes = new byte[1024];
		DataInputStream in = new DataInputStream(new FileInputStream(f));
		while ((in != null) && ((length = in.read(bytes)) != -1)) {
			op.write(bytes, 0, length);
		}
		op.close();
		in.close();
		response.flushBuffer();
	}
	
}
